using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Threading;
using Prism.Commands;
using Prism.Mvvm;
using JMClient.Models.PhysicalComponents;
using JMClient.Service;
using JMClient.Views;
using Prism.Dialogs;
using Prism.Events;
using Prism.Navigation.Regions;

namespace JMClient.ViewModels
{
    public class DeviceEntityViewModel : BindableBase
    {
        private readonly IEventAggregator _ea;
        public DeviceEntity Entity { get; set; }

        public int Id => Entity.Id;
        public string Name => Entity.Name;
        public bool Using => Entity.Using;
        public string Description => Entity.Description;

        public string ModuleRegion => Entity.ModuleRegion;

        // 这里简单用类型决定状态色，如需更复杂逻辑可扩展
        public IBrush StatusBrush => Using
            ? Brushes.Goldenrod
            : Brushes.ForestGreen;

        public DelegateCommand OpenCommand { get; set; }
        public DelegateCommand NotifyParentCommand { get; }
        private readonly IDialogService _dialogService;
        public IAsyncCommand AsyncOpenCommand { get; }
        public DelegateCommand LoadComponentsCommand { get; set; }

        public DeviceEntityViewModel(IEventAggregator eventAggregator,IRegionManager regionManager, IDialogService dialogService)
        {
            //_entity = entity;
            _ea = eventAggregator;
            NotifyParentCommand = new DelegateCommand(OnNotifyParent);
            
            OpenCommand = new DelegateCommand( () =>
            {
            
            });
            _dialogService = dialogService;

            AsyncOpenCommand = new AsyncDelegateCommand(OpenAsync);
        }
        private async Task OpenAsync()
        {
            var parameters = new DialogParameters
            {
              
            };

            // 如果你的 IDialogService 有异步 API，可直接 await；若只有回调形式，先 ShowDialog 然后等待 VM.Ready 的方式：
            // 方式 A: 通过容器预创建 SandboxWindowViewModel 实例并传入参数（更容易 await Ready）
            // 这里示例使用回调 + 小等待作为通用做法：

            var tcs = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);

            _dialogService.ShowDialog(nameof(SandboxWindow), parameters, r =>
            {
                // 回调在对话关闭时触发；我们不在此处完成 Ready
                // 如果需要等待对话关闭，可 tcs.TrySetResult(r);
            });

            // 等待 Render 周期以确保对话已显示并布局
            await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render);
            await Task.Delay(20);

            // 如果 SandboxWindowViewModel 或传入的 ContentVM 暴露 Ready，推荐 await 它：
            // await sandboxVm.Ready; 

            // 此时对话应该已经显示并渲染，可以继续后续逻辑（例如向 Region 注册视图等）
        } 
        public void OnNotifyParent()
        {
            // 发布事件，并传递当前项的标识或其它信息
            _ea.GetEvent<TriggerParentEvent>()
                .Publish(this);
        }
    }
    
    public class TriggerParentEvent : PubSubEvent<object> { }
}